package yth.api.train.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import yth.api.train.entity.TrainCustomer;
import yth.api.train.model.LogisticsUserModel;
import yth.api.train.model.RetError;
import yth.api.train.model.RetMsg;
import yth.api.train.model.RetSuccess;
import yth.api.train.model.TrainCustomerModel;
import yth.api.train.service.ITrainCustomerService;
 

/**
 * 收货人接口
 *
 */
@RestController
@RequestMapping("/train")
public class TrainCustomerController {

	
	private static Logger logger=LoggerFactory.getLogger(TrainCustomerController.class);
	 
	@Autowired
	private RestTemplate restTemplate;
	
	@Autowired
	private  ITrainCustomerService trainCustomerService;
	
	@RequestMapping(value="customers",method=RequestMethod.GET)
	public RetMsg findAll() {
		logger.info("/train/customers ---- start ");
		RetMsg retMsg=null;
		try {
			List<TrainCustomer> list= trainCustomerService.selectAll(new BigDecimal(11));
			List<TrainCustomerModel> models=new ArrayList<>(); 
			for (TrainCustomer trainCustomer : list) {
				 models.add(TrainCustomerModel.copyFrom(trainCustomer)); 
			}
			retMsg=new RetSuccess(models);
		} catch (Exception e) {
			retMsg=new RetError(40001, e.toString());
			logger.error(e.toString());
		}
		logger.info("train/customers ---- end ");
		return retMsg;
	}
	
	@GetMapping("/user")
	@HystrixCommand(fallbackMethod="findUserFallback")
	 public LogisticsUserModel findUser() {
		LogisticsUserModel model=new LogisticsUserModel();
//		断路器 不能加try catch,不抛异常就不走 fallback 。
		model=this.restTemplate.getForObject("http://ms-gateway-zuul-filter-fallback/api-user/logistics/user/1", LogisticsUserModel.class);
		 
		return model;
	 }
	
	public LogisticsUserModel findUserFallback() {
		LogisticsUserModel user=new LogisticsUserModel();
		user.setAccount("000");
		return user;
	}
}
















